package modes

import (
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/Luxurioust/excelize"
)

/*
 * 描述: 题库表
 *
 * Status 状态  0 启用  1 禁用
 * s_type 0单选 1多选 2对错 3 不定项
 *
 *****************************/

type TopicLib struct {
	Id        int64       `json:"t_id" `                        //题库ID
	SId       int64       `json:"t_sid" xorm:"sid"`             //科目ID
	PId       int64       `json:"t_pid" xorm:"pid"`             //项目ID
	NId       int64       `json:"t_nid" xorm:"n_id"`            //试卷ID(套题ID)
	Name      string      `json:"t_name" xorm:"name"`           //题干名称
	Answer    string      `json:"t_answer" xorm:"answer"`       //答案解析
	Selec     string      `json:"t_selec" xorm:"selec"`         //答案选项
	Price     int64       `json:"t_price" xorm:"price"`         //价格
	At        int64       `json:"t_at" xorm:"at"`               //时间
	Fraction  int         `json:"t_fraction" xorm:"fraction"`   //题分数 加
	Deduction int         `json:"t_deduction" xorm:"deduction"` //题分数
	SType     int         `json:"t_type" xorm:"s_type"`         //题库类型
	Start     int         `json:"t_start" xorm:"start"`         //状态
	Text      []TopicText `json:"Text" xorm:"-"`                //状态
	Log       []TopicLog  `json:"Log" xorm:"-"`                 //记录
}

type JoinTopicLog struct {
	TopicLib `xorm:"extends"`
	TopicLog `xorm:"extends"`
}

func (this *TopicLib) TableName() string {
	return "topiclib"
}

func (this *TopicLib) Save() (int64, error) {
	this.At = time.Now().Unix()
	this.Start = 0
	this.Price = this.Price / 100
	return Db(0).Insert(this)
}

func (this *TopicLib) Get() (bool, error) {
	return Db(0).Get(this)
}

func (this *TopicLib) IdDel() (int64, error) {
	where := fmt.Sprintf("id = %d", this.Id)
	return Db(0).Where(where).Delete(this)
}

func (this *TopicLib) update(where string, field string) (int64, error) {
	return Db(0).Where(where).Cols(field).Update(this)
}

func (this *TopicLib) IdSet(field string) (int64, error) {
	where := fmt.Sprintf("id = %d", this.Id)
	return this.update(where, field)
}

func (this *TopicLib) PLists(val *Pager, uid int64) error {
	list := make([]TopicLib, 0)
	val.TName = "topiclib"
	val.Page--
	if val.Page <= 0 {
		val.Page = 0
	}
	var field, sort string
	field = fmt.Sprintf("%s.s_type", val.TName) // 题库类型
	if 0 == val.Rules {
		sort = fmt.Sprintf("%s asc", field)
	} else {
		sort = fmt.Sprintf("%s desc", field)
	}
	where := fmt.Sprintf("start = 0")
	val.Total, _ = Db(1).Table(val.TName).
		Where(where).
		Where(val.ToWhere()).
		Count(this)

	err := Db(1).Table(val.TName).
		Where(where).
		Where(val.ToWhere()).
		OrderBy(sort).
		Limit(val.Count, val.Page*val.Count).
		Find(&list)
	if err == nil {
		for i, row := range list {
			list[i].Text, _ = GetToptext(row.Id)
			list[i].Log, _ = GetToplog(row.Id, uid)
		}
		val.List = list
	}
	return err
}
func GetToptext(tid int64) ([]TopicText, error) {
	list := make([]TopicText, 0)
	w := fmt.Sprintf("tid = %d ", tid)
	err := Db(1).
		Where(w).
		Find(&list)
	return list, err
}
func GetToplog(tid int64, uid int64) ([]TopicLog, error) {
	list := make([]TopicLog, 0)
	w := fmt.Sprintf("tid = %d and uid = %d ", tid, uid)
	err := Db(0).
		Where(w).
		Find(&list)
	return list, err
}

func (this *TopicLib) Count(where string) (int64, error) {
	var val TopicLib
	return Db(0).Where(where).Count(&val)
}
func (this *TopicLib) where(fage, count, page int, where, field string) ([]TopicLib, error) {
	list := make([]TopicLib, 0)
	var err error
	if field == "" {
		field = "id"
	}
	page--
	if 0 == fage { // 从小到大排序
		err = Db(0).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(0).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}

func (this *TopicLib) ParsingFile(file_url string) error {

	// 首先读excel
	xlsx, err := excelize.OpenFile(file_url)
	if err != nil {
		return nil
	}
	rows, err := xlsx.GetRows(xlsx.GetSheetName(xlsx.GetActiveSheetIndex()))
	var val TopicText
	t_id := 0
	for i, row := range rows {
		if i == 0 {
			continue
		}
		k := strings.Contains(row[0], ".")

		if k != true {
			var lib TopicLib
			lib.SId = this.SId
			lib.PId = this.PId
			lib.Name = row[1]
			lib.Selec = row[2]
			lib.Answer = row[3]
			lib.Price, _ = strconv.ParseInt(row[4], 10, 64)
			lib.SType, _ = strconv.Atoi(row[5])
			lib.Fraction, _ = strconv.Atoi(row[6])
			lib.Deduction, _ = strconv.Atoi(row[7])
			lib.Save()
			t_id = int(lib.Id)
		} else {
			val.TQues = row[1]
			val.Selec = row[2]
			val.TId = int64(t_id)
			val.Save()
		}
	}
	return err
}
